import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import {Button, Form, Row, Col, Card, Spin, message as msg} from 'antd';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import {injectIntl, language} from './intl';
import {getDetail} from './api';
import WrappedSelect from '../common/WrappedSelect';
import {salesOPSubmitLimitType} from '../Enum';
import WrappedInputNumber from '../common/WrappedInputNumber';
import WrappedDatePicker from '../common/WrappedDatePicker';
const typeList = salesOPSubmitLimitType.toList(language);
export class UpdatePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {},
    };

    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data
                    });
                this.setState({
                    loading: false
                });
            });
    }

    componentWillUnmount() {
        this.isunmount = true;
    }

    handleFilterChange = (value, name) => {
        if(name === 'submitEndDay' && value === 31)
            msg.warn(this.props.intl.formatMessage({
                id: 'message.submitEndDay',
                defaultMessage: '这是月底最后一天'
            }));
        if(name === 'submitNoticeEndDay' && value === 31)
            msg.warn(this.props.intl.formatMessage({
                id: 'message.submitEndDay',
                defaultMessage: '这是月底最后一天'
            }));
        if(name === 'expirationDate' && value === null)
            msg.warn(this.props.intl.formatMessage({
                id: 'message.expirationDate',
                defaultMessage: '此设置永远有效'
            }));
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }

    onClickReturnBtn = () => {
        this.props.onCancel();
    }

    onSubmit = () => {
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }

    render() {
        const {data} = this.state;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const validateType = !data.type && this.state.validate ? 'error' : null;
        const validateSubmitBeginDay = !data.submitBeginDay && this.state.validate ? 'error' : null;
        const validateSubmitEndDay = !data.submitEndDay && this.state.validate ? 'error' : null;
        const validateEffectiveDate = !data.effectiveDate && this.state.validate ? 'error' : null;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'updatePanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.brandCode',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item}>
                                        {`(${data.brandCode})${data.brandName}`}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.dealerCode',
                                        defaultMessage: '总代'
                                    })}{...FORM_OPTIONS.item}>
                                        {`(${data.dealerCode})${data.dealerName}`}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'queryPanel.form.type',
                                        defaultMessage: '提报时效类型'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateType} required>
                                        <WrappedSelect
                                            allowClear
                                            name="type"
                                            value={data.type}
                                            options={typeList}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.submitBeginDay',
                                        defaultMessage: '每月提报开始日'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateSubmitBeginDay} required>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitBeginDay"
                                            value={data.submitBeginDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.submitEndDay',
                                        defaultMessage: '每月提报结束日'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateSubmitEndDay} required>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitEndDay"
                                            value={data.submitEndDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.submitNoticeBeginDay',
                                        defaultMessage: '提报提醒开始日'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitNoticeBeginDay"
                                            value={data.submitNoticeBeginDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.submitNoticeEndDay',
                                        defaultMessage: '提报提醒结束日'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitNoticeEndDay"
                                            value={data.submitNoticeEndDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.effectiveDate',
                                        defaultMessage: '生效日期'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateEffectiveDate} required>
                                        <WrappedDatePicker
                                            name="effectiveDate"
                                            value={data.effectiveDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.expirationDate',
                                        defaultMessage: '失效日期'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="expirationDate"
                                            value={data.expirationDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        {<Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'updatePanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpdatePanel.propTypes = {
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);

const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: data => dispatch(onSubmit(data)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url())
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
